/**
 * Created by sxx on 2017/5/3.
 */
import "./index.less";
import { projSts } from "../config.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.zh-CN.js";

import bidListTpl from "./apply_list.handlebars";
import bidListOperateTpl from "./apply_list_operate.handlebars";
import paginationTpl from "./paging.handlebars";

let token = sessionStorage.getItem('token');
let reseIndex = sessionStorage.getItem('reseIndex');

if(reseIndex=='05'){ // 审核员，可以操作
    $("#sample_1 thead tr").html("<th>供应商编号</th><th>供应商名称</th><th>简称</th><th>供应商等级</th><th>供应商状态</th><th>登录账号</th><th>操作</th>");
}

jQuery('.datetimepicker').datetimepicker({
    language: 'zh-CN',
    weekStart: 1,
    todayBtn: 1,
    autoclose: 1,
    todayHighlight: 1,
    startView: 2,
    minView: 2, //0表示分钟（默认），1表示小时，而2表示天
    forceParse: 0,
    showMeridian: 1,
    format: 'yyyy-mm-dd'///
});

var ApplyList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,
    data:{},
    init: function() {
        this.getData()
            .then(this.renderList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    },
    getData: function() {
        return new Promise((resolve, reject) => {
            let self = this;
            let data = self.data;
            let header = {
                    'access_token': token,
                    'login_type': 'ums',
                    "splrStatus": "02,03,04,05,06,07,08,09,10,11,12"
                };
            if(data.splrSts!='' && data.splrSts!=null){
                header.splrStatus = data.splrSts;
            }
            $.ajax({
                // url: HOST_ADDR + `/cpmp/splrMng/splrListByStatus/`,
                url: HOST_ADDR + `/cpmp/splrMng/splrList/`+this.pageNo+'/'+this.pageSize,
                type: 'post',
                dataType: 'json',
                headers: header,
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        console.log(resp);
                        resolve(resp);
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
    },
    // 渲染列表

    renderList: function(resp) {
        let self = ApplyList;
        // 处理数据begin
        let splrStatus = {
            "01":"注册",
            "02":"准入申请",
            "03":"预备供方",
            "04":"开发申请",
            "05":"合格供方",
            "06":"淘汰",
            "07":"黑名单",
            "08":"准入申请失败",
            "09":"开发申请失败",
            "10":"主数据申请失败",
            "11":"BPM申请成功",
            "12":"主数据申请"
        };
        let resultHtml = '';
        if(resp.data==''||resp.data==null){
            self.total = 0;
            self.isFirstPage = self.pageNo === 1;
            self.maxPage = 1;
            self.isLastPage = true;
        }else{
            self.total = resp.data.count;
            self.isFirstPage = self.pageNo === 1;
            self.maxPage = Math.ceil(self.total / self.pageSize);
            console.log(resp.data);
            $.each(resp.data.list,function(index,item){
                item.applyAvailabel = item.splrSts === "01";
                item.bindName = 0; //是否需要绑定登录账号
                if(item.loginAccount!=null && item.loginAccount!=''){
                    item.bindName = 1;
                }
                item.splrStsName = splrStatus[item.splrSts];
            });
            // 处理数据end
            if (self.pageNo * self.pageSize >= self.total) {
                self.isLastPage = true;
            } else {
                self.isLastPage = false;
            }
            if(reseIndex=='05'){
                resultHtml = bidListOperateTpl({ applyList: resp.data.list });
            }else{
                resultHtml = bidListTpl({ applyList: resp.data.list });
            }
        }
        $('.J_apply-list').html(resultHtml);
    },

    // 渲染分页
    renderPagination: function() {
        let self = ApplyList;
        let pageList = [];
        for (let i = 0; i < self.maxPage; i++) {
            pageList.push({ idx: i + 1 });
        }
        let paginationHtml = paginationTpl({
            begin: (self.pageNo - 1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index, item) => {
            if ($(item).data('index') === self.pageNo) {
                $(item).addClass('active');
            }
            var basepage = self.pageNo;
            if(basepage<=5){
                basepage = 5;
            }
            if((-5 <= (parseInt($(item).data('index'))-basepage)) && ((parseInt($(item).data('index'))-basepage)<=5)){
                $(item).removeClass('hidden');
                $(item).find("span").removeClass("hidden");
            }else{
                $(item).addClass('hidden');
                $(item).find("span").addClass("hidden");
            }
        });
    },

    // 绑定事件
    bindEvent: function() {
        let self = ApplyList;
        $('.J_prev').unbind().click(function() {
            if (self.pageNo > 1) {
                self.pageNo = self.pageNo - 1;
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }
        });
        $('.J_next').unbind().click(function() {
            console.log('J_next');

            if (self.pageNo < self.maxPage) {
                console.log('aaa');
                self.pageNo = self.pageNo + 1;
                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }

        });
        $('.page-item').off().on('click', function() {
            let $item = $(this);
            console.log('aaaa');
            if (!$item.hasClass('active')) {
                self.pageNo = $item.data('index');

                self.getData()
                    .then(self.renderList)
                    .then(self.renderPagination)
                    .then(self.bindEvent);
            }
        });

        //搜索
        $('.searchSplr').unbind().click(function(){
            var searNam = jQuery('.searNam').val();
            var searStatus = jQuery('.searStatus').val();
            var itdcCompy = jQuery('.itdcCompy').val();
            var searTimBgnStr = jQuery('.searTimBgnStr').val();
            var searTimEndStr = jQuery('.searTimEndStr').val();
            self.pageNo = 1;
            self.data = {};
            if (searNam != '' && searNam != null) {
                self.data.fullNam = searNam;
            }
            if (searStatus != '' && searStatus != null) {
                self.data.splrSts = searStatus;
            }
            if (itdcCompy != '' && itdcCompy != null) {
                self.data.itdcCompy = itdcCompy;
            }
            if (searTimBgnStr != '' && searTimBgnStr != null) {
                self.data.crtTimBgnStr = searTimBgnStr+" 00:00:00";
            }
            if (searTimEndStr != '' && searTimEndStr != null) {
                self.data.crtTimEndStr = searTimEndStr+" 23:59:59";
            }
            console.log(self.data);
            self.getData()
                .then(self.renderList)
                .then(self.renderPagination)
                .then(self.bindEvent);
        });


        // 重置密码         // 绑定账号
        $('.J_resetPasswd').unbind().click(function(){
            var splrId=$(this).parent().parent().attr("splrId");
            var data={};
            $.ajax({
                url: HOST_ADDR + `/cpmp/splrMng/resetPasswd`,
                type: 'post',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'ums',
                    "splrId": splrId
                },
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        console.log(resp);
                        self.getData()
                            .then(self.renderList)
                            .then(self.renderPagination)
                            .then(self.bindEvent);
                    } else {
                        alert(resp.msgInf);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        });
    },
};

App.init();
ApplyList.init();

